package com.ly.push.utils;


import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.ly.push.param.MyTimeProperties;
import com.ly.push.param.QyWpProperties;
import com.ly.push.param.WxMpProperties;
import com.ly.push.param.weather.WeatherInfo;
import com.ly.push.param.wx.QyWxRobot;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class QyWxUtils {

    @Resource
    WxMpProperties wxMpProperties;
    @Resource
    WeatherUtils weatherUtils;
    @Resource
    MyTimeProperties myTimeProperties;
    @Resource
    RainUtils rainUtils;
    @Resource
    QyWpProperties qyWpProperties;

    //企业微信接口：发送消息(POST)
    private static String sendMessageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";

    //企业微信获取token
    public String getToken(){
        //企业微信接口：获取TOKEN地址(GET)
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + qyWpProperties.getCorpId() + "&corpsecret=" + qyWpProperties.getSecret();;
        String  token = JSONObject.parseObject(HttpUtils.doGet(url)).getString("access_token");
        return token;
    }

    /**
     * 企业微信发送文本消息
     * @param userId 企业微信id，全部用户是"@all" 指定接收消息的成员，成员ID列表（多个接收者用‘|’分隔，最多支持1000个）
     * @param content 发送内容
     */
    public void sendTextMsg(String userId,String content){
        String  token = getToken();
        Map<String,Object> map = new HashMap<>();//要发送的消息结构体
        Map<String,Object> text = new HashMap<>();//消息正文
        map.put("touser",userId);//接收用户的ID，全部用户是"@all" 指定接收消息的成员，成员ID列表（多个接收者用‘|’分隔，最多支持1000个）
        map.put("msgtype","text");//消息类型，这里是text文本型
        text.put("content",content);//消息内容，最长不超过2048个字节，超过将截断（支持id转译）
        map.put("agentid",qyWpProperties.getAgentId());//企业微信中的小程序ID
        map.put("text",text);
        JSONObject res =  JSONObject.parseObject(HttpUtils.doPostJson(sendMessageUrl + token, JSONObject.toJSONString(map)));
        //返回：{"errcode":0,"errmsg":"ok","msgid":""} errcode为0表示成功
        System.out.println(res);
    }

    //调用这个无参方法，然后这个方法拼接参数调用有参方法
    public void sendTextCard(String userId,String title,String url,Integer index){
        //微信小表情网站：https://www.emojiall.com/zh-hans/platform-wechat
        StringBuffer msg = new StringBuffer();
        WeatherInfo weatherInfo = new WeatherInfo();
        switch (index){
            case 0:
                weatherInfo = weatherUtils.getWeather("山东省临沂市");
                break;
            case 1:
                weatherInfo = weatherUtils.getWeather("山东省临沂市",1);
                break;
        }
        String date = weatherInfo.getDate();
        String high = weatherInfo.getHigh();
        String low = weatherInfo.getLow();
        String fengxiang = weatherInfo.getFengxiang();
        String fengli = weatherInfo.getFengli();
        String type = weatherInfo.getType();
        String cityName = "山东❤临沂";
        //消息内容，微信显示不了太多，不要弄太多了
        msg.append("\uD83C\uDFF0城市：").append(cityName);
        if (index==0){
            msg.append("\n\uD83D\uDDD3日期：今天(").append(date).append(")");
        }else {
            msg.append("\n\uD83D\uDDD3日期：明天(").append(date).append(")");;
        }
        msg.append("\n\uD83C\uDF25天气：").append(type);
        msg.append("\n\uD83E\uDD75最高温度：").append(high);
        msg.append("\n\uD83E\uDD76最低温度：").append(low);
//        msg.append("\n☔︎降雨概率：").append("%");
        if (index==0){
            msg.append("\n\uD83D\uDCA8风向：").append(fengxiang).append("~").append(fengli);
        }else {
            msg.append("\n\uD83D\uDCA8风向：").append(fengxiang);
        }
//        msg.append("\n\uD83D\uDCA8风向：").append(fengxiang).append("~").append(fengli);
//        msg.append("\n\uD83C\uDF05日出时间：");
//        msg.append("\n\uD83C\uDF07日落时间：");
//        msg.append("\n\uD83C\uDFD6生活指数：");
        Map<String,String> map = rainUtils.getRain3();
        msg.append("\n\uD83D\uDD24：").append(map.get("en"));
        msg.append("\n\uD83D\uDC8C：").append(map.get("zh"));
//        message.append("\n\uD83D\uDC91");//恋爱用的
        sendTextCard(userId,title, String.valueOf(msg),url);
    }

    /**
     * 企业微信发送模板
     * @param userId    企业微信id
     * @param title     推送卡片标题
     * @param message   消息内容
     * @param url       url地址
     */
    public void sendTextCard(String userId, String title, String message, String url){
        String  token = getToken();
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> textcard = new HashMap<>();
        map.put("touser",userId);
        map.put("msgtype","textcard");
        map.put("agentid",qyWpProperties.getAgentId());
        textcard.put("title",title);
        textcard.put("description",message);
        textcard.put("url",url);
        map.put("textcard",textcard);
        JSONObject res =  JSONObject.parseObject(HttpUtils.doPostJson(sendMessageUrl + token, JSONObject.toJSONString(map)));
        System.out.println(res);
    }


    /*********************************************企业微信机器人*********************************************/
    public void test(){
        QyWxRobot robot = new QyWxRobot();
        //机器人地址
        robot.setWebhookAddress(wxMpProperties.getWebhook());
//        //1.第一种情况：发送文本消息
//        robot.setContent("你好");
//        List<String> memberList = new ArrayList<>();
//        memberList.add("@all");
//        robot.setMemberList(memberList);
//        robot.setMsgType("text");

//         //2.第二种情况，发送图片消息
//         robot.setMsgType("image");
//         robot.setSavePath("D:/Desktop/123/m5.jpg");

//        //3.第三种情况，发送机器人消息
//        robot.setMsgType("news");
//        robot.setTitle("标题");
//        robot.setDescription("内容");
//        robot.setUrl("url");
//        // robot.setImageUrl("url")括号中的url为上传到服务器的地址
//        robot.setImageUrl("url");

        robot.setMsgType("markdown");
        System.out.println(toSend(robot));
    }

    public String toSend(QyWxRobot robot)  {
        List<String> memberList = robot.getMemberList();
        String str = "";
        String str1 = "";
        String mobileList = "";
        String strMember = "";
        switch (robot.getMsgType()){
            case "text":
                if (!Strings.isNullOrEmpty(robot.getMobileList())) {
                    mobileList = robot.getMobileList();
                } else {
                    mobileList = "";
                }
                for (int i = 0; i < memberList.size(); i++) {
                    if (i == memberList.size() - 1) {
                        strMember += "\"" + memberList.get(i) + "\"";
                    } else {
                        strMember += "\"" + memberList.get(i) + "\"" + ",";
                    }
                }
                String[] members = new String[memberList.size()];
                for (int i = 0; i < memberList.size(); i++) {
                    members[i] = memberList.get(i);
                }
                str = "{\n" +
                        "\t\"msgtype\": \"" + robot.getMsgType() + "\",\n" +
                        "    \"text\": {\n" +
                        "        \"content\": \"" + robot.getContent() + "\",\n" +
                        "        \"mentioned_list\":[" + strMember + "],\n" +
                        "        \"mentioned_mobile_list\":[\"" + mobileList + "\"]\n" +
                        "    }\n" +
                        "}";
                break;
            case "image":
                //图片base64加密的值
                robot.setImageBase64Value(getImageStr(robot.getSavePath()));
                //图片md5加密的值
                try {
                    robot.setImageMd5Value(DigestUtils.md5Hex(new FileInputStream(robot.getSavePath())));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                str = "{\n" +
                        "    \"msgtype\": \"" + robot.getMsgType() + "\",\n" +
                        "    \"image\": {\n" +
                        "        \"base64\": \"" + robot.getImageBase64Value() + "\",\n" +
                        "        \"md5\": \"" + robot.getImageMd5Value() + "\"\n" +
                        "    }\n" +
                        "}";
                break;
            case "news":
                //图片+文字消息
                robot.setTitle(!Strings.isNullOrEmpty(robot.getTitle()) ? robot.getTitle() : "");
                str = "{\n" +
                        "    \"msgtype\": \"" + robot.getMsgType() + "\",\n" +
                        "    \"news\": {\n" +
                        "       \"articles\" : [\n" +
                        "           {\n" +
                        "               \"title\" : \"" + robot.getTitle() + "\",\n" +
                        "               \"description\" : \"" + robot.getDescription() + "\",\n" +
                        "               \"url\" : \"" + robot.getUrl() + "\",\n" +
                        "               \"picurl\" : \"" + robot.getImageUrl() + "\"\n" +
                        "           }\n" +
                        "        ]\n" +
                        "    }\n" +
                        "}";
                break;
            case "markdown":
//                str = "{\n" +
//                        "\t\"msgtype\": \"" + robot.getMsgType() + "\",\n" +
//                        "    \"markdown\": {\n" +
//                        "        \"content\": \"" + robot.getContent() + "\",\n" +
//                        "    }\n" +
//                        "}";
                WeatherInfo weatherInfo = weatherUtils.getWeather("临沂");
                String date = weatherInfo.getDate();
                String hl = weatherInfo.getLow() +"~" +weatherInfo.getHigh();
                String fengxiang = weatherInfo.getFengxiang();
                String fengli = weatherInfo.getFengli();
                String birthday1 = myTimeProperties.getBirthday1();
                String birthday2 = myTimeProperties.getBirthday2();
                String day1 = myTimeProperties.getDay1();
                // calcBirthday 方法是计算还距离日期还有多少天
                // calcDay 是计算已经过去多少天
                String rain = rainUtils.getRain();
                str1 = "{\n" +
                        "    \"msgtype\": \""+robot.getMsgType()+"\",\n" +
                        "    \"markdown\": {\n" +
                        "        \"content\": \"<font color=\\\"#FF1493\\\">"+date+"</font>\\n\n" +
                        "         >地区：<font color=\\\"#FF0000\\\">山东❤临沂</font>\n" +
                        "         >天气：<font color=\\\"#FF1493\\\">"+weatherInfo.getType()+"</font>\n" +
                        "         >气温：<font color=\\\"#EA7F7F\\\">"+hl+"</font>\n" +
                        "         >风：<font color=\\\"#FFA500\\\">"+fengxiang+"~~"+fengli+"</font>\"\n" +
                        "    }\n" +
                        "}\n";
                str = "{\n" +
                        "    \"msgtype\": \""+robot.getMsgType()+"\",\n" +
                        "    \"markdown\": {\n" +
                        "        \"content\": \"<font color=\\\"#FF1493\\\"></font>\\n\n" +
                        "         >今天是我们<font color=\\\"#FF1493\\\">恋爱</font>的第<font color=\\\"#FF1493\\\">"+String.valueOf(TimeUtils.calcDay(day1))+"</font>天\n" +
                        "         >距离<font color=\\\"#FF1493\\\">"+myTimeProperties.getName2()+"</font>的生日还有<font color=\\\"#FF1493\\\">"+String.valueOf(TimeUtils.calcBirthday(birthday2))+"</font>天\n" +
                        "         >距离<font color=\\\"#FF1493\\\">"+myTimeProperties.getName1()+"</font>的生日还有<font color=\\\"#FF1493\\\">"+String.valueOf(TimeUtils.calcBirthday(birthday1))+"</font>天\n" +
                        "         >距离<font color=\\\"#FF1493\\\">周年纪念日</font>还有<font color=\\\"#FF1493\\\">"+String.valueOf(TimeUtils.calcBirthday(day1))+"</font>天\n" +
                        "         ><font color=\\\"#C71585\\\">"+rain+"</font>\"\n" +
                        "    }\n" +
                        "}\n";

                send(robot.getWebhookAddress(), str1);
                break;
        }
        return send(robot.getWebhookAddress(), str);
    }

    //根据图片地址转换为base64编码字符串
    public static String getImageStr(String imgFile) {
        //要想发送图片内容需要将图片加密转化成base64编码
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 图片加密
        Base64.Encoder er= Base64.getEncoder();
        return er.encodeToString(data);
    }

    public static String send(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        JSONObject jsonObject = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流（设置请求编码为UTF-8）
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 获取请求返回数据（设置返回数据编码为UTF-8）
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            jsonObject = JSONObject.parseObject(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return jsonObject.toString();
    }

}
